
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.

#TwistedSim: Made some minor modification so it would 
# connect the ip passed in sys.argv

"""
An example client. Run simpleserv.py first before running this.
"""

from twisted.internet import reactor, protocol


# a client protocol

class EchoClient(protocol.Protocol):
    """Once connected, send a message, then print the result."""
    
    def connectionMade(self):
        #TwitedSim: replaced raw_input with fixed value.
        #value = raw_input("Enter a string: ")
        value = "Hello"
        self.transport.write(value)

    def dataReceived(self, data):
        "As soon as any data is received, write it back."
        print "Server said:", data
        self.transport.loseConnection()
    
    def connectionLost(self, reason):
        print "connection lost"

class EchoFactory(protocol.ClientFactory):
    protocol = EchoClient

    def clientConnectionFailed(self, connector, reason):
        print "Connection failed - goodbye!"
        reactor.stop()
    
    def clientConnectionLost(self, connector, reason):
        print "Connection lost - goodbye!"
        reactor.stop()

# this connects the protocol to a server runing on port 8000
def main():
    #TwistedSim: Modifying so it would connect to the address
    # passed in the sys args.
    import sys
    if len(sys.argv) != 2:
        print "Wrong number of arguments"
        print "Usage: " + sys.argv[0] + "serverAddress"
        return 
    f = EchoFactory()
    #reactor.connectTCP("localhost", 8000, f)
    serverAddr = sys.argv[1]
    reactor.connectTCP(serverAddr, 8000, f)
    reactor.run()

# this only runs if the module was *not* imported
if __name__ == '__main__':
    main()